/* 
 * Copyright (c) 2012 Aalto University and University of Helsinki
 * MIT License
 * see LICENSE.txt for more information
 */

$(function() { // DOCUMENT READY

  // if and only if on the search results page the parts variable contains the string search. 
  if ($('.uri-input-box').val() !== undefined && parts.indexOf('search') == -1) { queryConceptTree($('.uri-input-box').val()); }
  
  var textColor = $('.search-parameter-highlight').css('color');

  if(parts.indexOf('search') == -1) { // Disabled if on the search results page.
  /*
   * Event handler for clicking the preflabel and making a selection of it for copy pasting.
   */
    $('.search-parameter-highlight').click(
      function() {
        var text = $('.prefLabel')[0];    
        var range;
        if (document.body.createTextRange) { // ms
          range = document.body.createTextRange();
          range.moveToElementText(text);
          range.select();
        } else if (window.getSelection) { // moz, opera, webkit
          var selection = window.getSelection();            
          range = document.createRange();
          range.selectNodeContents(text);
          selection.removeAllRanges();
          selection.addRange(range);
        }
        return false;
      }
      );
  }

  // Event handler for restoring the DOM back to normal after the focus is lost.
  $(':not(.search-parameter-highlight)').click(
      function(){
        $('#temp-textarea').remove();
        $('.search-parameter-highlight').css({'background': 'transparent', 'color': textColor});
      }
  );

  // sets the language cookie for 365 days
  function setLangCookie(lang) {
    createCookie('ONKI_LANGUAGE', lang, 365);
  }

  // Event handlers for the language selection links for setting the cookie
  $('#language-fi').click(function() { setLangCookie('fi'); });
  $('#language-sv').click(function() { setLangCookie('sv'); });
  $('#language-en').click(function() { setLangCookie('en'); });
  
  $('.uri-input-box').click(function() { this.select(); });
  
  // Calling 'chosen' plugin  to take over the select-box css
  $('.chosen-select').chosen({disable_search_treshold: 10});

  // Setting the language parameters according to the cookie if found.
  var search_all = readCookie('ONKI_SEARCH_ALL');
  var search_selection = document.getElementById('all-languages-false');
  
  // taking the url parameters given by the controller 
  // into parts used for determining if we are on the search listings
  parts = parts.split('/'); // splits pathname, e.g.
  
  var rest_url = rest_base_url; 
  if (rest_url.indexOf('..') == -1 && rest_url.indexOf('http') == -1) { rest_url = location.protocol + '//' + rest_url; }
  
  // qlang is used in REST queries as a parameter. it is either
  // - "&lang=<code>" when searching in a specific language
  // - "" when searching in all languages
  var qlang = "&lang=" + lang;
  
  // setting the focus to the search box on default
  $("#search-vocab-parameter").focus();

  // enabling jquery ui tooltips
  $(document).tooltip();

  // setting the search language parameter according to the all languages
  // radiobutton
  if (search_selection)
    search_selection.checked = true;

  if (search_all === '1') {
    search_selection = document.getElementById('all-languages-true');
    qlang = "";
    if (search_selection)
      search_selection.checked = true;
  }

  $('#all-languages-false').click(function() {
    qlang = "&lang=" + lang;
  });

  $('#all-languages-true').click(function() {
    qlang = "";
  });
  
  var searchTerm = "";
  // calls for another function to highlight search term in the labels.
  if (getUrlParams().q) {
    localSearchHighlight(decodeURI(getUrlParams().q.replace(/\*/g, '')));
    searchTerm = getUrlParams().q;
  }
  
  var searchInAllLanguages = "";
  if (getUrlParams().all === 1) {
    searchInAllLanguages = "&all=1";
  }
  
  // activates a jquery drop-down plugin for the feedback page.
  $('select#drop-down').selectmenu({
    style : 'dropdown',
    width : 305,
    maxHeight : 400
  });

  // activates the anythingSlider plug-in for the infobox picture slider.
  $('#slider').anythingSlider({
    easing : "easeInOutExpo", // Anything other than "linear" or "swing"
    // requires the easing plugin
    autoPlay : true, // This turns off the entire FUNCTIONALY, not just
    // if it starts running or not.
    delay : 6000, // How long between slide transitions in AutoPlay mode
    startStopped : false, // If autoPlay is on, this can force it to start
    // stopped
    animationTime : 600, // How long the slide transition takes
    hashTags : false, // Should links change the hashtag in the URL?
    buildNavigation : true, // If true, builds and list of anchor links to
    // link to each slide
    pauseOnHover : true, // If true, and autoPlay is enabled, the show
    // will pause on hover
    startText : " ", // Start text
    stopText : " ", // Stop text
    buildArrows : false
  });

  var NoResultsLabel = [ {
    "label" : noResultsTranslation,
    "vocab" : ""
  } ];
 
  // make the search button pretty by calling jquery ui
  $('#search-all-button').button();
  
  // disables the button with an empty search form 
  $('#search-vocab-parameter').keyup(function() {
    var empty = false;
    $('#search-vocab-parameter').each(function() {
      if ($(this).val().length === 0) {
        empty = true;
      }
    });

    if (empty) {
      $('#search-all-button').attr('disabled', 'disabled');
    } else {
      $('#search-all-button').attr('disabled', false);
    }
  });
  
  // activates jquery autocomplete for the search fields
  var autoC = $("#search-vocab-parameter")
  .autocomplete(
  {
    source : function(request, response) {
      $
      .ajax({
        url : rest_url + 'search?query=' +
          request.term + "*" + qlang + '&vocab=' + vocab,
        dataType : "json",
        success : function(data) {
          if (data.results.length === 0)
            response(NoResultsLabel);

          else {
            response($
              .map(
                data.results
                .filter(function(item) {
                  // either we are performing a local search
                  // or the concept is native to the vocabulary
                  return (vocab !== "" || !item.exvocab);
                }),
                function(item) { // slice
                  // limits
                  // results
                  // shown
                  var name = (item.altLabel ? item.altLabel +
                    " \u2192 " +
                    item.prefLabel : item.prefLabel);
                  item.label = name;
                  return item;
                }));
          }
        }
      });
    },
    delay : autocomplete_delay, // time (in milliseconds)
    // before autocomplete
    // activates i.e. sends a
    // request to the REST
    // interface
    minLength : autocomplete_activation,

    select : function(event, ui) { // what happens when
      // user clicks/uses autocomplete
      
      var localname = ui.item.localname;
      if (ui.item.exvocab || localname.substring(0, 7) === "http://") {
        localname = "?uri=" + encodeURIComponent(ui.item.localname);
      }
      if (ui.item.label === NoResultsLabel[0].label) {
        event.preventDefault();
        return false;
      }
      // replaced complex logic with path_fix that should always work.
      location.href = path_fix + ui.item.vocab + '/' + lang + '/page/' + localname;
    },
    focus : function(event, ui) {
      return false; // Prevent the widget from inserting
    // the value.
    }
  }).data("autocomplete");

  $("button#send-feedback").button({
    icons : {
      primary : "ui-icon-mail-closed"
    }
  });
  
  // Some form validation for the feedback form
  $("#send-feedback")
  .click(
    function() {
      $(".error").remove();
      var emailMessageVal = $("#message").val();
        
      if (emailMessageVal === '') {
        $("#message")
        .after(
          '<ul class="error"><li><span class="errors">Value is required and can\'t be empty</ul></li></span>');
        return false;
      }
      return true;
    });

  // activation and initialisation for the jquery waypoints plug-in used for
  // the scrollable search results.
  var $loading = $("<div class='loading-text'><p class='conceptlabel'>" + loading_text + "&hellip;<span class='spinner'/></p></div>"), $footer = $('footer'), opts = {
    offset : '100%'
  };
  var currentlyLoading = false;
  var offcount = 1;
  var number_of_hits = document.getElementsByClassName("concept-hit").length;
  var $ready = $("<div class='loading-text'><p class='conceptlabel'>" + results + " " + number_of_hits + " " + results_disp +"</p></div>");
  var $displayed = $("<div class='result-count-text'><p class='conceptlabel'>" + waypoints_disp + number_of_hits + waypoints_res + "</p></div>");
  
  if (parts[parts.length-1].indexOf('search') !== -1 && number_of_hits !== 0) { // if we are in the search page with some results
    if (number_of_hits < waypoint_results * offcount) { 
      $('#vocab-content').append($ready);
    }
    else {
      $('#vocab-content').prepend($displayed);
      $footer.waypoint(function(event, direction) {
        if (currentlyLoading === false) {
          currentlyLoading = true;
          $displayed.detach();
          $footer.waypoint('remove');
          if (number_of_hits >= waypoint_results * offcount)
            $('#vocab-content').append($loading);

          $.ajax({
            url : window.location.pathname + '?q=' + searchTerm + '&offset=' + offcount * waypoint_results + searchInAllLanguages,
            success : function(data) {
              currentlyLoading = false;
              $loading.detach();
              if (data === '') {
                $('#vocab-content').append($ready);
                return false;
              }
              $('#vocab-content').append(data);
              $footer.waypoint(opts);
              number_of_hits = document.getElementsByClassName("concept-hit").length;
              $ready = $("<div class='loading-text'><p class='conceptlabel'>" + results + " " + number_of_hits + " " + results_disp +"</p></div>");
              offcount++;
              if (getUrlParams().q) {
                localSearchHighlight(decodeURI(getUrlParams().q.replace(/\*/g, "")));
              }
              if (number_of_hits < waypoint_results * offcount) {
                $('#vocab-content').append($ready);
                currentlyLoading = true; // fixes problem where the script wouldn't realize that it had already displayed all the results
              }
              $displayed = $("<div class='result-count-text'><p class='conceptlabel'>" + waypoints_disp + number_of_hits + waypoints_res + "</p></div>");
              $('#vocab-content').prepend($displayed);
              return false;
            }
          });
        }
      }, opts);
    }
  }
  
});
